<?php

class Mageex_Robot_Helper_Amazon extends Mage_Core_Helper_Abstract
{
	public function awsRequest($region, $params, $publicKey, $privateKey)
	{
		libxml_use_internal_errors(true);
		$method 	= "GET";
		$host 		= "ecs.amazonaws.".$region;
		$uri 		= "/onca/xml";
		
		$params["Service"] 			= "AWSECommerceService";
		$params["AWSAccessKeyId"] 	= $publicKey;
		
		$timestamp = time() + 10000;
		$params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z",$timestamp);	
		$params["Version"] = "2012-01-16";
		ksort($params);
		
		$canonicalizedQuery = array();
		foreach ($params as $param=>$value) {
			$param = str_replace("%7E", "~", rawurlencode($param));
			$value = str_replace("%7E", "~", rawurlencode($value));
			$canonicalizedQuery[] = $param."=".$value;
		}
		$canonicalizedQuery = implode("&", $canonicalizedQuery);
		$stringToSign = $method."\n".$host."\n".$uri."\n".$canonicalizedQuery;   
		$signature 	= base64_encode(hash_hmac("sha256", $stringToSign, $privateKey, True));  
		$signature 	= str_replace("%7E", "~", rawurlencode($signature));  
		// string request
		$request 	= "http://".$host.$uri."?".$canonicalizedQuery."&Signature=".$signature;
		//exit;
		if ( function_exists('curl_init') ) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Konqueror/4.0; Microsoft Windows) KHTML/4.0.80 (like Gecko)");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_URL, $request);
			curl_setopt($ch, CURLOPT_TIMEOUT, 60);
			$response = curl_exec($ch);	
			if (!$response) {
				$return["error"]["reason"] = "cURL Error";
				$return["error"]["message"] = Mage::helper('robot')->__("cURL Error Number ").curl_errno($ch).": ".curl_error($ch);	
				return $return;
			}
			curl_close($ch);
		} else { 				
			$response = @file_get_contents($request);
			if (!$response) {
				$return["error"]["reason"] = "cURL Error";
				$return["error"]["message"] = Mage::helper('robot')->__("cURL is not installed on this server!");	
				return $return;		
			}
		}
		//echo $request;
		$response = simplexml_load_string($response);
		if ($response === False) {
			$emessage = Mage::helper('robot')->__("Failed loading XML, errors returned: ","wprobot");
			foreach(libxml_get_errors() as $error) {
				$emessage .= $error->message . ", ";
			}	
			libxml_clear_errors();
			$return["error"]["reason"] = "XML Error";
			$return["error"]["message"] = $emessage;	
			return $return;			
		} else {
			return $response;
		}
	}
	
	// Post of product
	public function amazonPost($keywords, $numberRecord, $start, $optional)
	{
		$searchIndex 	= $optional['searchIndex'];
		$browseNode		= $optional['browseNode'];	
		//Review searchindex
		if($searchIndex == ""){
			$searchIndex = "All";
		}
		
		if($keywords == "" && $browsenode  == "") {
			$return["error"]["reason"] = "No keyword";
			$return["error"]["message"] = Mage::helper('robot')->__("No keyword or BrowseNode specified.");	
			return $return;	
		}
		$arrResult 	= array();
		$imagePath 	= Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'robot/rates/';
		$affKey 	= Mage::helper('robot/config')->getAffKey();
		if(!$affKey){
			$affKey = 'YourAssociateTagHere';
		}
		$publicKey 	= Mage::helper('robot/config')->getApiKey(); 
		$privateKey = Mage::helper('robot/config')->getSecretKey();
		
		$site = Mage::helper('robot/config')->getSite();	
		if($site == "us") {$site = "com";}
		if($site == "uk") {$site = "co.uk";} 	
		
		if($browsenode == "") {$browsenode = 0;}
		
		$params = array(
			"Operation"		=> "ItemSearch",
			"AssociateTag"	=> $affKey,
			"Keywords"		=> $keywords,
			"SearchIndex"	=> $searchIndex,
			"MerchantId"	=> "All",
			"ItemPage"		=> 1,
			"ReviewSort"	=> "-HelpfulVotes",
			"TruncateReviewsAt"		=> "5000",
			"IncludeReviewsSummary"	=> "True",
			"ResponseGroup"	=> "Large"
		);
		$publicKey 	= Mage::helper('robot/config')->getApiKey(); 
		$privateKey = Mage::helper('robot/config')->getSecretKey();
		$response 	= $this->awsRequest($site, $params, $publicKey, $privateKey);
		
		if (!$response->Items->Item) {
			$return["error"]["reason"] = "No content";
			$return["error"]["message"] = Mage::helper('robot')->__("No (more) products found for this keyword <b>\"$keywords\"</b>.");	
			return $return;			
		}
		$numOfItems = $response->Items->TotalResults;
		$totalPages = $response->Items->TotalPages;
		
		$page = $start;
		
		while($page <= $totalPages) {
			
			$paramsPage = array(
				"Operation"		=> "ItemSearch",
				"AssociateTag"	=> $affKey,
				"Keywords"		=> $keywords,
				"SearchIndex"	=> $searchIndex,
				"MerchantId"	=> "All",
				"ItemPage"		=> $page,
				"ReviewSort"	=> "-HelpfulVotes",
				"TruncateReviewsAt"		=>"5000",
				"IncludeReviewsSummary"	=> "True",
				"ResponseGroup"			=> "Large"
			);
			
			$responsePage = $this->awsRequest($site, $paramsPage, $publicKey, $privateKey);
			$responseTotal = $responsePage->Items->TotalResults;
			if (!$responsePage) {
				$return["error"]["reason"] = "Request fail";
				$return["error"]["message"] = Mage::helper('robot')->__("API request could not be sent.");	
				return $return;						
			}
			
			if (isset($responsePage->Error)) {
				$message = '<p>'.Mage::helper('robot')->__("There was a problem with your Amazon API request. This is the error Amazon returned:").'</p>
				<p><i><b>'.$responsePage->Error->Code.':</b> '.$responsePage->Error->Message.'</i></p>';	
				$return["error"]["reason"] = "API fail";
				$return["error"]["message"] = $message;	
				return $return;
			}	

			if (isset($responsePage->Items->Request->Errors->Error->Code)) {
				$message = '<p>'.Mage::helper('robot')->__("There was a problem with your Amazon API request. This is the error Amazon returned:").'</p>
				<p><i><b>'.$responsePage->Items->Request->Errors->Error->Code.':</b> '.$responsePage->Items->Request->Errors->Error->Message.'</i></p>';
				$return["error"]["reason"] = "API fail";
				$return["error"]["message"] = $message;	
				return $return;
			}			
			
			if ($responseTotal == 0) {
				
				$return["error"]["reason"] = "No content";
				$return["error"]["message"] = Mage::helper('robot')->__("No (more) products found for keyword <b>$keywords</b>.");	
				return $return;			
			}	
			$cItem =0;
			foreach($responsePage->Items->Item as $item) {
				$skipit = 0;
				$skip 	= Mage::helper('robot/config')->getSkip();
				if($skip == "nodescription" || $skip == "desorthumb") {
					if(empty($item->MediumImage->URL) && empty($item->SmallImage->URL)) {
						$skipit = 1;
					}
				}	
				if($skip == "nothumb" || $skip == "desorthumb") {
					if(empty($item->EditorialReviews->EditorialReview->Content)) {
						$skipit = 1;
					}
				}			
				
				$cItem++;
				if($cItem <= $numberRecord && $skipit==0){
					$desc = "";					
					if (isset($item->EditorialReviews->EditorialReview)) {
						foreach($item->EditorialReviews->EditorialReview as $descs) {
							$desc .= $descs->Content;
						}		
					}	
					
					$elength = Mage::helper('robot/config')->getDesLength();
					if ($elength != 'full') {
						$desc = strip_tags($desc,'<br>');
						$desc = substr($desc, 0, $elength);
					}
					$shortDescription = $desc;
					$features = "";
					if (isset($item->ItemAttributes->Feature)) {	
						$features = "<ul>";
						foreach($item->ItemAttributes->Feature as $feature) {
							$posx = strpos($feature, "href=");
							if ($posx === false) {
								$features .= "<li>".$feature."</li>";		
							}
						}	
						$features .= "</ul>";				
					}
					
					$timg 	= $item->MediumImage->URL;
					if($timg == "") {
						$timg = $item->SmallImage->URL;
					}				
					$thumbnail 	= '<a href="'.$item->DetailPageURL.'" rel="nofollow"><img style="float:left;margin: 0 20px 10px 0;" src="'.$timg.'" /></a>';					
					$link 		= '<a href="'.$item->DetailPageURL.'" rel="nofollow">'.$item->ItemAttributes->Title.'</a>';	
					
					//additional information of the product
					$additionalInfors = $item->ItemLinks->ItemLink;
					/*
					foreach ($additionalInfors as $additionalInfor) {
						echo $additionalInfor->URL;
						echo $technical = file_get_contents($additionalInfor->URL);
						break;
					}
					*/
					// REVIEWS -  Replace for Nov 11 API Change

					$product_review = $item->CustomerReviews->IFrameURL;
					$reviewsiframe 	= '<iframe style="margin-top: 10px;" src="'.$product_review.'" width="100%" height="450px"><p>Your browser does not support iframes.</p></iframe>';
					$revcontent = file_get_contents($product_review); 
					if (preg_match('~<body[^>]*>(.*?)</body>~si', $revcontent, $body)) { $reviewsnoiframe = str_replace('class="crVotingButtons">', "", $body[1]); } else {$reviewsnoiframe = "";} 
				
					$price = str_replace("$", "$ ", $item->OfferSummary->LowestNewPrice->FormattedPrice);
					
					$listprice = str_replace("$", "$ ", $item->ItemAttributes->ListPrice->FormattedPrice);

					if($price == "Too low to display" || $price == "Price too low to display") {
						$price = $listprice;
					}
					
					
					//$template from database
					$content = "Review by {author} for {link} Rating: {rating} {content}";
		
					preg_match('#\[has_reviews\](.*)\[/has_reviews\]#smiU', $template, $check);
					if ($check[0] != false) {
						if(empty($item->CustomerReviews->TotalReviews)) {
							$content = str_replace($check[0], "", $content);
						}
					}	
					$content = str_replace(array("[has_reviews]","[/has_reviews]"), "", $content);		
					preg_match('#\[has_listprice\](.*)\[/has_listprice\]#smiU', $template, $matches);//print_r($matches);
					if ($matches[0] != false) {
						if(empty($listprice)) {
							$content = str_replace($matches[0], "", $content);
						}
					}
					$content = str_replace(array("[has_listprice]","[/has_listprice]"), "", $content);
					
					$asin = $item->ASIN;			
					$content = str_replace("{title}", $item->ItemAttributes->Title, $content);
					$content = str_replace("{description}", $desc, $content);
					$content = str_replace("{features}", $features, $content);
					$content = str_replace("{thumbnail}", $thumbnail, $content);
					$content = str_replace("{smallimage}", $item->SmallImage->URL, $content);	
					$content = str_replace("{mediumimage}", $item->MediumImage->URL, $content);	
					$content = str_replace("{largeimage}", $item->LargeImage->URL, $content);
					$content = str_replace("{buynow}", '<a href="'.$item->DetailPageURL.'" rel="nofollow"><img src="'.$imagePath.'buynow-small.gif" /></a>', $content);		
					$content = str_replace("{buynow-big}", '<a href="'.$item->DetailPageURL.'" rel="nofollow"><img src="'.$imagePath.'buynow-big.gif" /></a>', $content);					
					$content = str_replace("{buynow-ger}", '<a href="'.$item->DetailPageURL.'" rel="nofollow"><img src="'.$imagePath.'buynow-ger.gif" /></a>', $content);					
					$content = str_replace("{price}", $price, $content);
					$content = str_replace("{listprice}", $listprice, $content);
					$savings = str_replace("$ ", "", $listprice) - str_replace("$ ", "", $price);
					$content = str_replace("{savings}", $savings, $content);
					$content = str_replace("{url}", $item->DetailPageURL, $content);	
					$content = str_replace("{avgrating}", $item->CustomerReviews->AverageRating, $content);	
					$content = str_replace("{reviewsnum}", $item->CustomerReviews->TotalReviews, $content);		
					$noqkeyword = str_replace('"', '', $keywords);
					$content = str_replace("{keyword}", $noqkeyword, $content);
					$content = str_replace("{Keyword}", ucwords($noqkeyword), $content);					
					$content = str_replace("{link}", $link, $content);
					$content = str_replace("{asin}", $asin, $content);
					$content = str_replace("{price-updating}", '[wpramaprice asin="'.$asin.'"]', $content);
					
					// rating
					if (strpos($content, "{rating}") != false) {			 
						$image = $this->starRating($item->CustomerReviews->AverageRating);
						$content = str_replace("{rating}",$image,$content);
					}	
					
					// reviews
					$content = str_replace("{reviews-url}", $product_review, $content);	
					//$content = str_replace("{reviews-iframe}", $reviewsiframe, $content);
					$content = str_replace("{reviews-iframe}", '[wpramareviews asin="'.$asin.'"]', $content);
					$content = str_replace("{reviews-noiframe}", $reviewsnoiframe, $content);					
					preg_match('#\{reviews(.*)\}#iU', $content, $rmatches);
					if ($rmatches[0] == false) {					
					} else {
						$content = str_replace($rmatches[0], '[wpramareviews asin="'.$asin.'"]', $content);				
					}	
					
					// split reviews into comments
					$dom = new DOMDocument();
					@$dom->loadHTML($reviewsnoiframe);	

					$xpath = new DOMXPath($dom);
					$paras = $xpath->query("//table[@class='crIFrameReviewList']//tr/td/div");
					
					$reviews = array();
					for ($y = 0;  $y < $paras->length; $y++ ) {  //$paras->length
						$para = $paras->item($y);
									
						$review = $dom->saveXml($para);	
						//$review = str_replace('', "", $review);
						//$review = str_replace('', "", $review);
						$review = str_replace('Permalink', "", $review);
						$review = str_replace('Report abuse', "", $review);
						$review = str_replace('See all my reviews', "", $review);
						$review = str_replace('<img src="http://g-ecx.images-amazon.com/images/G/01/x-locale/communities/reputation/c7y_badge_rn_1._V192249968_.gif" width="70" align="absmiddle" alt="(REAL NAME)" height="15" border="0" />', "", $review);
						//$review = preg_replace('#<div style="padding-top: 10px; clear: both; width: 100%;">(.*)<div class="reply">#smiU', '<div><div>', $review);
						$reviews[$y]["content"] = $review;						
					}	
					
					$xpath = new DOMXPath($dom);
					$paras = $xpath->query("//table[@class='crIFrameReviewList']//tr/td/div/div[3]/div/div/a/span");					
					for ($y = 0;  $y < $paras->length; $y++ ) {  //$paras->length
						$para = $paras->item($y);
						$author = $para->textContent; // $dom->saveXml($para);	
						
						$reviews[$y]["author"] = $author;						
					}
					
					
					if(!empty($item->MediumImage->URL)) {
						$largestimage = $item->MediumImage->URL;
					}elseif(!empty($item->SmallImage->URL)) {
						$largestimage = $item->SmallImage->URL;
					}elseif(!empty($item->LargeImage->URL)) {
						$largestimage = $item->LargeImage->URL;
					}					

					$customfield = array();
					$customfield["amazontitle"] 	= $item->ItemAttributes->Title;
					$customfield["amazonbinding"] 	= $item->ItemAttributes->Binding;
					$customfield["amazonsku"] 		= $item->ItemAttributes->SKU;
					$customfield["amazonbrand"] 	= $item->ItemAttributes->Brand;
					$customfield["amazonthumbnail"] = $largestimage;
					$customfield["amazonthumbnaillarge"] = $item->LargeImage->URL;					
					$customfield["amazonprice"] 	= $price;
					$customfield["amazonlink"] 		= $item->DetailPageURL;
					$customfield["amazonasin"] 		= $asin;
					$customfield["amazonrating"] 	= $item->CustomerReviews->AverageRating;
					$customfield["description"] 	= $shortDescription;	
					
					$single = array();
					$single["unique"] 	= $asin;
					$single["title"] 	= $item->ItemAttributes->Title;
					$single["content"] 	= $content;
					$single["comments"] = $reviews;	
					$single["customfield"] = $customfield;
										
					array_push($arrResult, $single);
							
				}else{
					return $arrResult;
				}
			}
			$page++;
		}
		
	}
	
	public function starRating($rating)
	{
		$imagepath = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'robot/rates/';
		if($rating>=0 && $rating <= 0.7) {
			$image = '<img src="'.$imagepath.'0-5.png" />';
		}
		if($rating>=1.3 && $rating <= 1.7) {
			$image = '<img src="'.$imagepath.'1-5.png" />';
		}
		if($rating>=2.3 && $rating <= 2.7) {
			$image = '<img src="'.$imagepath.'2-5.png" />';
		}
		if($rating>=3.3 && $rating <= 3.7) {
			$image = '<img src="'.$imagepath.'3-5.png" />';
		}
		if($rating>=4.3 && $rating <= 4.7) {
			$image = '<img src="'.$imagepath.'4-5.png" />';
		}
		if($rating>=0.8 && $rating <= 1.2) {
			$image = '<img src="'.$imagepath.'1.png" />';
		}
		if($rating>=1.8 && $rating <= 2.2) {
			$image = '<img src="'.$imagepath.'2.png" />';
		}
		if($rating>=2.8 && $rating <= 3.2) {
			$image = '<img src="'.$imagepath.'3.png" />';
		}
		if($rating>=3.8 && $rating <= 4.2) {
			$image = '<img src="'.$imagepath.'4.png" />';
		}
		if($rating>=4.8 && $rating <= 5) {
			$image = '<img src="'.$imagepath.'5.png" />';
		}
			 
		return $image;
	}
}